package cn.xuchunh.campusbbs.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import cn.xuchunh.campusbbs.AppContext;
import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.bean.User;

/**
 * Created by XuChunH on 2015/9/9.
 */
public abstract class BaseActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private boolean showHomeUp = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        beforeInitView();
        View content = getLayoutInflater().inflate(createContentRes(), null);
        setContentView(content);
        initView(content);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(showHomeUp);
            getSupportActionBar().setHomeButtonEnabled(showHomeUp);
            ViewCompat.setElevation(toolbar, getResources().getDimensionPixelSize(R.dimen.elevation));
        }
        afterInitView();
        AppContext.getInstance().pushActivity(this);
    }

    protected abstract int createContentRes();

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.slide_in, 0);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.slide_out);
    }

    @Override
    protected void onDestroy() {
        AppContext.getInstance().popActivity(this);
        super.onDestroy();
    }

    protected abstract void initView(View view);

    protected void beforeInitView() {
    }

    protected void afterInitView() {
    }

    public Toolbar getToolbar() {
        return toolbar;
    }

    protected void setShowHomeUp(boolean showHomeUp) {
        this.showHomeUp = showHomeUp;
    }

    protected void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    protected void showToast(int messageRes) {
        showToast(getString(messageRes));
    }

    protected User getUser() {
        return AppContext.getInstance().getUser();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home && showHomeUp) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
